package com.cans.ssoserver.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cans
 * @date 2018/6/19
 * @description 登陆验证拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 不需要拦截的路径
     */
    private String noInterceptUrl = "/sso/,/static/,/error";

    /**
     * Controller之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        String[] split = noInterceptUrl.split(",");
        for (String s : split) {
            if(requestURI.contains(s)){
                return true;
            }
        }

        Object ssoUser = request.getSession().getAttribute("ssoUser");
        if(ssoUser == null){
            //请求的路径
            String contextPath=request.getContextPath();
            response.sendRedirect(contextPath + "/sso/goLogin");
            return false;
        }
        return true;
    }

    /**
     * Controller之后,页面渲染之前执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 页面渲染之后调用,一般用于资源清理操作
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
